<?php defined('SYSPATH') or die('No direct script access.');

class sql {

    public static $FALSE = 0;
    public static $TRUE = 1;
    public static $ENTITY_VERSION_KEY = 'entity_version';
    public static $DECIMAL_PRECISION = 2;
    public static $TODAY;

    /**
     * Creates a string with values for SQL IN clause.
     * PHP PDO cannot do it.
     */
    public static function inClauseValues($array) {
        $placeholders = '';
        foreach ($array as $key => $value) {
            $value = str_replace("\\", "\\\\'", $value);
            $value = str_replace("'", "\\'", $value);
            $placeholders .= "'" . $value . "',";
        }
        return substr($placeholders, 0, -1);
    }

    public static function isPersistent($entity) {
        return ! empty($entity[sql::$ENTITY_VERSION_KEY]);
    }

    public static function orderBy($tableUuid, $queryString, $defaultOrderBy=null, $defaultOrder=null) {
        $sessionData = SessionData::instance();
        $sortOrder = $sessionData->getListOrder($tableUuid);
        if ($sortOrder == null && $defaultOrderBy) {
            if (! $defaultOrder) {
                $defaultOrder = SortOrder::$ASC;
            }
            $sortOrder = new SortOrder($defaultOrderBy, $defaultOrder);
            $sessionData->setListOrder($tableUuid, $sortOrder);

        }
        if ($sortOrder) {
            $queryString .= ' ORDER BY ' . $sortOrder->toSql();
        }
        return $queryString;
    }

    public static function queryToCount($query) {
        return preg_replace('/^SELECT (.*?) FROM/', 'SELECT count(*) FROM', $query);
    }

    public static function boolean($value) {
        if ($value) {
            return self::$TRUE;
        }
        else {
            return self::$FALSE;
        }
    }
}

sql::$TODAY = date('Y-m-d');